<template>
  <div class="task-list">
    <div class="header">
      <button @click="$emit('go-back')">返回</button>
      <div class="server-info">
        <span>服务器编号: {{ serverId }}</span>
        <span>操作系统版本: {{ osVersion }}</span>
      </div>
    </div>
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="task in tasks" :key="task.task_id">
          <td>{{ task.task_id }}</td>
          <td>{{ task.job_id }}</td>
          <td>{{ task.os }}</td>
          <td>{{ task.queue_time }}</td>
          <td>{{ task.start_time }}</td>
          <td>{{ task.end_time }}</td>
          <td>{{ task.cpu }}</td>
          <td>{{ task.memory }}</td>
          <td>{{ task.status }}</td>
          <td><ProgressBar :progress="task.progress" /></td>
          <td>
            <button 
              v-if="shouldShowLogButtons(task.status)" 
              @click="showTaskLog(task.task_id)"
            >
              日志查看
            </button>
            <button 
              v-if="shouldShowLogButtons(task.status)" 
              @click="downloadTaskLog(task.task_id)"
            >
              日志下载
            </button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">Previous</button>
      <span>Page {{ currentPage }}</span>
      <button @click="nextPage">Next</button>
    </div>
    <Toast v-if="showToast" :message="toastMessage" @close="showToast = false" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getTaskList, showTaskLog, downloadTaskLog } from '../../api/jobs'
import ProgressBar from '../common/ProgressBar.vue'
import Toast from '../common/Toast.vue'

export default {
  components: { ProgressBar, Toast },
  props: {
    job_id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const tasks = ref([])
    const currentPage = ref(1)
    const showToast = ref(false)
    const toastMessage = ref('')
    const serverId = ref('WN-' + Math.random().toString(36).substring(2, 8))
    const osVersion = ref(Math.random() > 0.5 ? 'Windows 10' : 'Ubuntu 20.04')
    
    const headers = [
      'Task编号', 'Job编号', '运行操作系统', '排队时间', 
      '开始时间', '结束时间', '占用cpu数量', '占用内存数量(GB)', 
      'status', '进度', '操作'
    ]

    const fetchTasks = async () => {
      try {
        const data = await getTaskList(currentPage.value, props.job_id)
        tasks.value = data.tasks
      } catch (error) {
        console.error('Failed to fetch tasks:', error)
      }
    }

    onMounted(fetchTasks)

    const nextPage = () => {
      currentPage.value++
      fetchTasks()
    }

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--
        fetchTasks()
      }
    }

    const shouldShowLogButtons = (status) => {
      return status !== 'waitting'
    }

    const showToastMessage = (message) => {
      toastMessage.value = message
      showToast.value = true
      setTimeout(() => {
        showToast.value = false
      }, 3000)
    }

    const showTaskLogHandler = async (task_id) => {
      try {
        const data = await showTaskLog(task_id)
        showToastMessage(`日志内容: ${data.log}`)
      } catch (error) {
        console.error('Failed to fetch task log:', error)
      }
    }

    const downloadTaskLogHandler = async (task_id) => {
      try {
        const response = await downloadTaskLog(task_id)
        const url = window.URL.createObjectURL(new Blob([response]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `${task_id}_log.txt`)
        document.body.appendChild(link)
        link.click()
        link.remove()
      } catch (error) {
        console.error('Failed to download task log:', error)
      }
    }

    return {
      tasks,
      headers,
      currentPage,
      showToast,
      toastMessage,
      serverId,
      osVersion,
      nextPage,
      prevPage,
      shouldShowLogButtons,
      showTaskLog: showTaskLogHandler,
      downloadTaskLog: downloadTaskLogHandler
    }
  }
}
</script>

<style scoped>
.task-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.server-info {
  display: flex;
  gap: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

button {
  padding: 5px 10px;
  cursor: pointer;
}
</style>
